import Storage from '../../utils/Storage'
import CacheMethod from "../../utils/CacheMethod";
import { ParamToObj, ObjToParam } from '../../utils/base'

import { getConfig } from '../../config'

export default (url, { pages = [], tabBar }) => {
    let hasOpenUrls = []
    pages.forEach(item => {
        if (item.open_url) {
            hasOpenUrls.push(item)
        }
    })
    let need_login = /need_login=1/.test(url)
    console.log('need_login', need_login)
    let option = ParamToObj(url)
    let routeKey = new RegExp('^[A-Za-z]*://open/([A-Za-z_].+)').exec(url)[1].split('?')[0]

    //获取 内部 url
    let OpenUrl = checkOpenUrl(url, routeKey, hasOpenUrls, pages, tabBar.list)
    if (!OpenUrl) { // 路由不存在
        console.log('路由不存在')
        return
    }
    let openType = getOpentype(url, OpenUrl, tabBar.list)
    OpenUrl = `${OpenUrl}?${ObjToParam(option)}`
    console.log(OpenUrl)

    if (need_login) {
        checkLogin(OpenUrl, openType)
    } else {
        next(openType, OpenUrl)
    }
}

const checkLogin = (OpenUrl, openType) => {
    let token = Storage.get(getConfig().TokenKey);
    if (!token) {
        CacheMethod.backRouter = ({ token, openId }) => {
            next(openType == 'navigateTo' ? 'redirectTo' : openType, OpenUrl)
        }
        next(openType == 'redirectTo' ? 'redirectTo' : 'navigateTo', `pages/login/index`)
        return
    } else {
        next(openType, OpenUrl)
        return
    }
}

const next = (openType, OpenUrl) => {
    uni[openType]({
        url: `/${OpenUrl}`,
        success: function (res) {
            console.log('res', res)
        },
        fail: function (err) {
            console.log('err', err)
        }
    })
}

const checkOpenUrl = (url, key, list, pages, tabBar) => {
    let uri = false
    if (key == 'maintab') {
        let index = parseInt(ParamToObj(url).index || 0)
        return index < tabBar.length ? tabBar[index].pagePath : tabBar[0].pagePath
    }
    list.forEach(item => {
        if (key == item.open_url) {
            uri = item.path
        }
    })
    pages.forEach(item => {
        if (key == item.path) {
            uri = item.path
        }
    })
    return uri
}
const getOpentype = (url, OpenUrl, tabBar) => {
    let isMaintab = checkoutMaintab(OpenUrl, tabBar)
    if (isMaintab) {
        return /open_type=reLaunch/.test(url) ? 'reLaunch' : 'switchTab'
    } else if (/open_type=redirectTo/.test(url)) {
        return 'redirectTo'
    } else if (/open_type=reLaunch/.test(url)) {
        return 'reLaunch'
    } else {
        return 'navigateTo'
    }
}
const checkoutMaintab = (OpenUrl, list) => {
    let state = false
    list.forEach(item => {
        if (OpenUrl == item.pagePath) {
            state = true
        }
    })
    return state
}

